import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:read_flutter/common/Tools.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:read_flutter/pages/bookInfo_page.dart';
import 'package:read_flutter/common/BookUtils.dart';
import 'package:cached_network_image/cached_network_image.dart';

class SearchPage extends StatefulWidget {
  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  TextEditingController _searchKey = TextEditingController();
  List<dynamic> bookList = [];
  bool isLoading = false;

  //搜索
  _searchBooks() async {
    setState(() {
      isLoading = true;
    });
    FocusScope.of(context).requestFocus(FocusNode());
    print(_searchKey.text);
    Response res = await Tools()
        .request('/search/bookname', {'bookname': _searchKey.text});
    print(res.data);
    if (res.data["code"] == "0") {
      bookList = res.data['result'];
    }else{
      Tools().showToast("获取书籍信息失败");
    }
    setState(() {
      isLoading = false;
    });
  }

  //书籍列表
  Widget bookListView() {
    return bookList.length == 0
        ? Center(
            child: Text('还没有书哦'),
          )
        : Container(
            child: Scrollbar(
            child: ListView.builder(
              itemBuilder: (BuildContext context, int index) {
                return bookItem(index);
              },
              itemCount: bookList.length,
            ),
          ));
  }

  //书Item
  Widget bookItem(int index) {
    Map<String, dynamic> book = bookList[index];
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.only(bottom: 5.0),
        padding: EdgeInsets.all(5.0),
        decoration: BoxDecoration(
          color: Color(0xffeeeeee),
        ),
        child: Row(
          children: <Widget>[
            Container(
              child: Image(

               image: CachedNetworkImageProvider(book['Cover']),
                width: 80.0,
                height: 110.0,
              ),
            ),
            Expanded(
                child: Container(
              padding: EdgeInsets.all(5.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Container(
                    child: Text(
                      book['BookName'].toString(),
                      overflow: TextOverflow.clip,
                      softWrap: false,
                      maxLines: 1,
                      style: TextStyle(
                        fontSize: 18.0,
                      ),
                    ),
                  ),
                  Container(
                    child: Text(
                      '作者:' + book['Author'].toString(),
                      overflow: TextOverflow.ellipsis,
                      softWrap: false,
                      maxLines: 1,
                      style:
                          TextStyle(fontSize: 12.0, color: Color(0xff666666)),
                    ),
                  ),
                  Container(
                    height: 40.0,
                    child: Text(
                      book["Intro"].toString(),
                      overflow: TextOverflow.ellipsis,
                      softWrap: true,
                      maxLines: 3,
                      style:
                          TextStyle(fontSize: 10.0, color: Color(0xff999999)),
                    ),
                  ),
                  Container(
                    child: Text(
                      "最新章节:" + book['Latestchapters'].toString(),
                      overflow: TextOverflow.ellipsis,
                      softWrap: false,
                      maxLines: 1,
                      style:
                          TextStyle(fontSize: 12.0, color: Color(0xff333333)),
                    ),
                  )
                ],
              ),
            ))
          ],
        ),
      ),
      onTap: () async {
        BookInfo bookInfo = await BookTools().getBookInfoWithLink(book);

        Navigator.of(context).push(MaterialPageRoute(builder: (_) {
          return BookInfoPage(bookInfo);
        }));
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Container(
            child: TextField(
              controller: _searchKey,
              style: TextStyle(fontSize: 17.0, color: Colors.white),
              autocorrect: false,
              onEditingComplete: _searchBooks,
              decoration: InputDecoration(
                border: InputBorder.none,
                hintText: '搜索书名',
                hintStyle: TextStyle(fontSize: 17.0, color: Colors.blueGrey),
              ),
            ),
          ),
        ),
        body: Stack(
          children: <Widget>[
            GestureDetector(
              behavior: HitTestBehavior.translucent,
              child: bookListView(),
              onTap: () {
                FocusScope.of(context).requestFocus(FocusNode());
              },
            ),
            loadProgressHUD()
          ],
        ));
  }

  //Loading HUD
  loadProgressHUD() {
    return Offstage(
      offstage: !isLoading,
      child: Container(
          width: double.infinity,
          height: double.infinity,
          color: Color.fromRGBO(0, 0, 0, 0.7),
          child: Center(
              child: Container(
            width: 80.0,
            height: 80.0,
            color: Colors.white,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                SpinKitCircle(
                  color: Colors.blue,
                  size: 25.0,
                ),
              ],
            ),
          ))),
    );
  }
}
